<template>
  <div id="adv-box" ref="workBox">
    <h1 class="title">广告管理</h1>
    <div class="main-cont">
      <v-toolbar @click="handleToolClick"></v-toolbar>
      <div class="table-cont mt10">
        <el-table :data="tableData" :height="height">
          <el-table-column label="广告图片">
            <template slot-scope="scope">
              <img :src="scope.row.ImageUrl" />
            </template>
          </el-table-column>
          <el-table-column prop="Title" label="广告名称"></el-table-column>
          <el-table-column label="创建日期">
            <template slot-scope="scope">
              {{ dateTransfer(scope.row.Created) }}
            </template>
          </el-table-column>
          <el-table-column label="设置">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="modifyAds(scope.row)">修改</el-button>
              <el-button type="text" size="mini" @click="delAds(scope.row.Id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <v-dialog
      :title="editMode === 'ADD' ? '新建广告':'修改广告'"
      :isVisible="dialogFormVisible"
      @close="closeDialog">
      <template slot="dialog-cont">
        <el-form :model="form" ref="form" :rules="rules" class="dialog-main dialogForm">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="广告名称" prop="Title">
                <el-input v-model="form.Title" placeholder="请输入广告名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="应用类别" >
                <el-select v-model="form.Type" placeholder="请选择应用类别" popper-class="zIndex-popper" @change="handleTypeChange">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="开始日期" prop="BeginDate">
                <el-date-picker
                  v-model="form.BeginDate"
                  type="date"
                  placeholder="请选择开始日期"
                  popper-class="zIndex-popper"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期" prop="EndDate">
                <el-date-picker
                  v-model="form.EndDate"
                  type="date"
                  placeholder="请选择结束日期"
                  popper-class="zIndex-popper"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="BeginTime">
                <el-time-select
                  v-model="form.BeginTime"
                  :picker-options="{
                    start: '00:00',
                    step: '00:01',
                    end: '24:00'
                  }"
                  placeholder="请选择开始时间"
                  popper-class="zIndex-popper"
                >
                </el-time-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="EndTime">
                <el-time-select
                  v-model="form.EndTime"
                  :picker-options="{
                    start: '00:00',
                    step: '00:01',
                    end: '24:00'
                  }"
                  placeholder="请选择结束时间"
                  popper-class="zIndex-popper"
                >
                </el-time-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="是否需要登录" prop="IsLogin">
                <el-checkbox v-model="isLogin">需要登录</el-checkbox>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="应用链接" prop="Url" v-if="isH || isQ">
                <el-input v-model="form.Url" placeholder="请输入应用链接"/>
              </el-form-item>
              <el-form-item label="布局视图" prop="ContentLayoutId" v-else-if="isV">
                <el-select v-model="form.ContentLayoutId" placeholder="请选择布局视图" popper-class="zIndex-popper" >
                  <el-option
                    v-for="item in optionsCtL"
                    :key="item.Title"
                    :label="item.Title"
                    :value="item.Id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="广告图片" prop="ImageUrl" v-else>
                <v-upload title="选择广告图片" type="ads" :picUrl="form.ImageUrl" :size="{width:1242, height:620}" @change="handlePicChange"></v-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <template v-if="isQ">
              <el-col :span="12">
                <el-form-item label="应用上传" prop="AppUrl">
                  <el-input v-model="form.AppUrl" v-show="false"/>
                  <v-upload title="选择应用上传" type="app" showType="w" :picUrl="form.AppUrl" @change="handlePicChange"></v-upload>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="广告图片" prop="ImageUrl">
                  <v-upload title="选择广告图片" type="ads" :picUrl="form.ImageUrl" :size="{width:1242, height:620}" @change="handlePicChange"></v-upload>
                </el-form-item>
              </el-col>
            </template>
            <template v-if="isH || isV">
              <el-col :span="12">
                <el-form-item label="广告图片" prop="ImageUrl">
                  <v-upload title="选择广告图片" type="ads" :picUrl="form.ImageUrl" :size="{width:1242, height:620}" @change="handlePicChange"></v-upload>
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </el-form>
      </template>
      <template slot="dialog-btns">
        <div class="form-buttons">
          <el-button @click="resetForm" size="mini">重置</el-button>
          <el-button @click="closeDialog" size="mini">关闭</el-button>
          <el-button type="primary" @click="submitForm" size="mini">确定</el-button>
        </div>
      </template>
    </v-dialog>
  </div>
</template>
<script>
  import VToolbar from '../../comm/iToolbar/iToolbar'
  import VDialog from '../../comm/iDialog/iDialog'
  import VUpload from '../../comm/iUpload/iUpload'
  import api from '../../../../api/url'
  import ajax from '../../../../api/ajax/ajax'
  export default {
    components: {
      VToolbar,
      VDialog,
      VUpload
    },
    data () {
      let checkDate = (rule, value, callback) => {
        let form = this.form
        if (form.BeginDate && form.EndDate) {
          if (form.BeginDate > form.EndDate) {
            callback(new Error('开始日期不能大于结束日期'))
          }
          callback()
        }
        callback()
      }
      let checkTime = (rule, value, callback) => {
        let form = this.form
        if (form.EndTime && form.BeginTime) {
          if (form.BeginTime > form.EndTime) {
            callback(new Error('开始时间不能大于结束时间'))
          }
          callback()
        }
        callback()
      }
      return {
        rules: {
          Title: [
            { required: true, message: '请填写广告名称', trigger: 'blur' }
          ],
          ImageUrl: [
            { required: true, message: '请选择封面图片', trigger: 'blur' }
          ],
          AppUrl: [
            { required: true, message: '请上传应用', trigger: 'blur' }
          ],
          Url: [
            { required: true, message: '请填写应用链接', trigger: 'blur' }
          ],
          ContentLayoutId: [
            { required: true, message: '请选择布局视图', trigger: 'blur' }
          ],
          BeginDate: [
            { validator: checkDate }
          ],
          EndDate: [
            { validator: checkDate }
          ],
          BeginTime: [
            { validator: checkTime }
          ],
          EndTime: [
            { validator: checkTime }
          ]
        },
        tableData: [],
        dialogFormVisible: false,
        editMode: 'ADD',
        height: null,
        options: [{
          value: 'H',
          label: 'H5应用'
        }, {
          value: 'Q',
          label: '轻应用'
        }, {
          value: 'V',
          label: '视图应用'
        }],
        optionsCtL: [],
        form: {
          Title: '',
          AppUrl: '',
          Type: '',
          BeginDate: '',
          EndDate: '',
          BeginTime: '',
          EndTime: '',
          IsLogin: '',
          Url: '',
          ImageUrl: ''
        },
        initData: {},
        isLogin: false,
        isH: false,
        isQ: false,
        isV: false
      }
    },
    methods: {
      // 工具栏操作
      handleToolClick (opt) {
        switch (opt) {
          case 'add':
            this.addAds()
            break
          default:
            break
        }
      },
      // 获取广告列表
      getAdsList () {
        ajax.get(api.QUERY_ADS).then(res => {
          this.tableData = res
        }).catch(() => {})
      },
      // 新建广告
      addAds () {
        this.editMode = 'ADD'
        this.dialogFormVisible = true
      },
      // 修改广告
      modifyAds (data) {
        this.form = JSON.parse(JSON.stringify(data))
        this.initData = JSON.parse(JSON.stringify(data))
        if (this.form.IsLogin === '1') {
          this.isLogin = true
        } else {
          this.isLogin = false
        }
        this.editMode = 'EDIT'
        this.handleTypeChange(this.form.Type)
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      },
      // 广告删除
      delAds (id) {
        this.$confirm('确定要删除该广告吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          ajax.get(api.DELETE_ADS_DELETE, {id: id}).then(res => {
            if (res.Code === 0) {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
            }
            this.getAdsList()
          }).catch(() => {})
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 选择图片处理
      handlePicChange (data) {
        switch (data.type) {
          case 'ads':
            this.form.ImageUrl = data.url
            break
          case 'app':
            this.form.AppUrl = data.url
            break
          default:
            break
        }
      },
      // 提交表单
      submitForm () {
        let msg = '新建成功'
        let port = api.ADD_ADS_CREATE
        if (this.editMode === 'EDIT') {
          port = api.UPDATE_ADS_UPDATE
          msg = '修改成功'
        }
        if (this.isLogin) {
          this.form.IsLogin = '1'
        } else {
          this.form.IsLogin = '0'
        }
        this.$refs['form'].validate((valid) => {
          if (valid) {
            ajax.post(port, this.form).then(res => {
              if (res.Code === 0) {
                this.$message({
                  message: msg,
                  type: 'success'
                })
              }
              this.closeDialog()
              this.getAdsList()
            })
          } else {
            return false
          }
        })
      },
      // 初始化表单
      initForm (formName) {
        this.$refs[formName].resetFields()
        this.form = {
          Title: '',
          AppUrl: '',
          Type: '',
          BeginDate: '',
          EndDate: '',
          BeginTime: '',
          EndTime: '',
          IsLogin: '',
          Url: '',
          ImageUrl: ''
        }
        this.isLogin = false
        this.isH = false
        this.isQ = false
        this.isV = false
      },
      // 重置
      resetForm () {
        this.initForm('form')
        if (this.editMode === 'EDIT') {
          this.form = { ...this.initData }
          this.handleTypeChange(this.form.Type)
        }
      },
      // 关闭弹窗
      closeDialog () {
        this.initForm('form')
        this.dialogFormVisible = false
      },
      // 应用分类下拉框触发事件
      handleTypeChange (val) {
        switch (val) {
          case 'H':
            this.isH = true
            this.isQ = false
            this.isV = false
            break
          case 'Q':
            this.isQ = true
            this.isH = false
            this.isV = false
            break
          case 'V':
            this.isV = true
            this.isH = false
            this.isQ = false
            // 获取布局视图
            ajax.get(api.QUERY_LAYOUT_LIST).then(res => {
              this.optionsCtL = res
            })
            break
          default:
            this.isV = false
            this.isH = false
            this.isQ = false
            break
        }
      },
      // 日期转换
      dateTransfer (time) {
        return new Date(time * 1000).getFullYear() + '/' + (new Date(time * 1000).getMonth() + 1) + '/' + new Date(time * 1000).getDate()
      }
    },
    created () {
      this.$nextTick(() => {
        this.height = this.$refs.workBox.offsetHeight - 138
      })
      this.getAdsList()
    }
  }
</script>
<style lang="stylus">
  #adv-box
    height 100%
    overflow hidden
    .checked
      display block
      margin-left 15px
      width 32px
      height 32px
      background url('') no-repeat center center
    .title
      height 60px
      padding 15px
      line-height 30px
      font-size 18px
      font-weight normal
      background #fff
    .mt10
      margin-top 10px
    .main-cont
      padding 10px 0 0 10px
    .table-cont
      img
        height:30px;
        max-width:50px
</style>
